using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using EzDeploy.Resources;
using Ionic.Zip;

namespace EzDeploy.Core
{
    public class ZipAssemblyCommand : IZipAssemblyCommand
    {
        public Result Run(IEnumerable<DeployGridItem> items, Project project)
        {
            if(!File.Exists(project.AssemblyFile))
                return new Result(ResultType.Error, string.Format(MessageResource.MainAssemblyNotFoundFmt, Path.GetFileName(project.AssemblyFile)));

            try
            {
                int count = 0;
                string zipFile = Path.Combine(project.DeployedDirectory, Path.GetFileNameWithoutExtension(project.AssemblyFile) + ".zip");

                if (!project.OverWriteFile && File.Exists(zipFile))
                    return new Result(ResultType.Error, string.Format(MessageResource.ZipOperationFileAlreadyExistFmt, Path.GetFileName(zipFile)));
                
                using (var zip = new ZipFile())
                {
                    zip.AddFile(project.AssemblyFile, string.Empty);
                    count++;

                    foreach (DeployGridItem item in items)
                    {
                        if (item.DeploymentType == DeploymentType.Include)
                        {
                            if (File.Exists(item.ItemFullPath))
                            {
                                zip.AddFile(item.ItemFullPath, string.Empty);
                                count++;
                            }
                        }
                    }

                    zip.Save(zipFile);
                    zip.Dispose();
                }

                return new Result(ResultType.Success, string.Format("Zipping {0} file(s) to '{1}' success.", count.ToString(CultureInfo.InvariantCulture), zipFile));
            }
            catch (Exception ex)
            {
                return new Result(ResultType.Error, string.Format("Error zipping file(s).{1}Exception: {0}", ex.Message, Environment.NewLine));
            }
        }
    }
}
